#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年1月6日

@author: chenyongbing
'''
import sys,os,commands
current_dir = os.path.dirname(__file__)

import logging,logging.config
sys.path.append(os.path.join(current_dir,'../../'))
from base.PyMySQL import ConnectMySQL

from base.PyEmail import *
from base.localConfig import baseLocalConfig

import sys,datetime
zhimind_host = baseLocalConfig.mysqlConfig['zhimind']['host']
zhimind_port = baseLocalConfig.mysqlConfig['zhimind']['port']
zhimind_user = baseLocalConfig.mysqlConfig['zhimind']['user']
zhimind_passwd = baseLocalConfig.mysqlConfig['zhimind']['passwd']
zhimind_db = baseLocalConfig.mysqlConfig['zhimind']['db']
myZhimind = ConnectMySQL(host=zhimind_host, user=zhimind_user, password=zhimind_passwd, db=zhimind_db)




class VerifyStatData(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        
    def verify_data(self,tab='avg_day_stats_by_group',day=None):
        if day==None:
            day =(datetime.date.today()-datetime.timedelta(1)).strftime('%Y-%m-%d')
        pass
    
        query = 'select count(*) from %s where day="%s"'%(tab,day)
        count = myZhimind.SelectCount(query)
        return count
    

    def verify_day_data(self,day=None):
        tabs = ['avg_day_stats_by_group','city_mac_customer_stats','comp_mac_customer_stats',
                'day_customer_type_stats','day_rank_stats','mac_customer_stats','mac_walkby_stats',
                'prov_mac_customer_stats','avg_hour_stats_by_group','hour_stats_by_group'
                ]
        for tab in tabs:
            count = self.verify_data(tab=tab, day=day)
            logging.info('Day:%s Tab:%s Count:%s.'%(day,tab,count))
            if count==0:
                return False
        return True
    def verify_week_data(self,day=None):
        tabs = ['week_customer_type_stats','week_rank_stats']        
        for tab in tabs:
            count = self.verify_data(tab=tab, day=day)
            logging.info('Day:%s Tab:%s Count:%s.'%(day,tab,count))
            if count==0:
                return False
        return True
    def verify_month_data(self,day=None):
        tabs = ['month_customer_type_stats','month_rank_stats']
        for tab in tabs:
            count = self.verify_data(tab=tab, day=day)
            logging.info('Day:%s Tab:%s Count:%s.'%(day,tab,count))
            if count==0:
                return False
        return True
    def verify_quarter_data(self,day=None):
        tabs = ['quarter_customer_type_stats','quarter_rank_stats']
        for tab in tabs:
            count = self.verify_data(tab=tab, day=day)
            logging.info('Day:%s Tab:%s Count:%s.'%(day,tab,count))
            if count==0:
                return False
        return True
    
    
    def verify_all_tab(self,day=None,timeType = 'day'):
        errMsg = []
        if day==None:
            day = (datetime.date.today()- datetime.timedelta(1)).strftime('%Y-%m-%d')
        day_date = datetime.date(int(day[:4]),int(day[5:7]),int(day[8:10]))
        
        tom_day = day_date + datetime.timedelta(1)
        
        if timeType == 'day':
            ret = self.verify_day_data(day=day)
            if ret==False:
                logging.error('Verify Day Data:ERROR.')
                errMsg.append('Verify Day Data:ERROR.')
            else:
                logging.info('Verify Day Data:Success.')
        if day_date.weekday() == 6 and timeType == 'week':
            week_day = (day_date - datetime.timedelta(6)).strftime('%Y-%m-%d')
            ret = self.verify_week_data(day=week_day)
            if ret==False:
                logging.error('Verify Week Data:ERROR.')
                errMsg.append('Verify Week Data:ERROR.')
            else:
                logging.error('Verify Week Data:Success.')
        if tom_day.day==1 and timeType == 'month':
            month_day = day_date.strftime('%Y-%m')+'-01'
            ret = self.verify_month_data(day=month_day)
            if ret==False:
                logging.error('Verify Month Data:ERROR.')
                errMsg.append('Verify Month Data:ERROR.')
            else:
                logging.info('Verify Month Data:Success.')
        if tom_day.day==1 and tom_day.month in (1,4,7,10) and timeType == 'quarter':
            if tom_day.month==1:
                quarter_day = day_date.strftime('%Y')+'-10-01'
            elif tom_day.month==4:
                quarter_day = day_date.strftime('%Y')+'-01-01'
            elif tom_day.month==7:
                quarter_day = day_date.strftime('%Y')+'-04-01'
            elif tom_day.month==10:
                quarter_day = day_date.strftime('%Y')+'-07-01'
            ret = self.verify_quarter_data(day=quarter_day)
            if ret==False:
                logging.error('Verify Quarter Data:ERROR.')
                errMsg.append('Verify Quarter Data:ERROR.')
            else:
                logging.info('Verify Quarter Data:Success.')
        if len(errMsg)==0:
            logging.info('Verify All Data:Success.')
        else:
            return '\n'.join(errMsg)
        return True
    
    
    def verify_rawdata_backup(self,backPath='/Udisk/rawdata/',day=None,minSize = 1024*1024*1024):
        if day==None:
            day = (datetime.date.today()- datetime.timedelta(1)).strftime('%Y-%m-%d')
            
        backFile = backPath+'/rawdata.%s.txt.tar.gz'%day
        if os.path.exists(backFile) and os.path.getsize(backFile)>minSize:
            return True
        else:
            False
    
    
if __name__=='__main__':
    logging.basicConfig(level = logging.INFO)
    
    from zhimind_data_check import myZhimindDataCheck
    
    import argparse,re,datetime,time
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--day',metavar=u"day",default=None)
    parser.add_argument('--rawbackup',metavar=u"rawdata backup path",default='/Udisk/rawdata/')
    parser.add_argument('--rawbackupsize',metavar=u"rawdata backup size",default=1024*1024*1024)
    parser.add_argument('--tolist',metavar=u"chen.yongbing@zhimatech.com",default='chen.yongbing@zhimatech.com')
    parser.add_argument('--timetype',metavar=u"timetype : day \ week \ month \ quarter",default='day')
    parser.add_argument('--prerun',action='store_true',help='pre run')
    args = parser.parse_args()
    tolist = args.tolist
    day = args.day
    rawbackup = args.rawbackup
    rawbackupsize = args.rawbackupsize
    timeType = args.timetype
    prerun = args.prerun
    if day==None and prerun==False:
        yesterday = (datetime.date.today()- datetime.timedelta(1)).strftime('%Y-%m-%d')
    elif day==None and prerun==True:
        yesterday = (datetime.date.today()).strftime('%Y-%m-%d')
    else:
        yesterday = (datetime.date(int(day[:4]),int(day[5:7]),int(day[8:10]))- datetime.timedelta(1)).strftime('%Y-%m-%d')
    logging.info('check day: %s'%yesterday)
    myVerifyStatData = VerifyStatData()
    
    check_rawdata_backup = myVerifyStatData.verify_rawdata_backup(backPath=rawbackup, day=day, minSize=rawbackupsize)
    errMsg = myVerifyStatData.verify_all_tab(day=day,timeType = timeType)
    sub ='后台数据验证及rawdata备份验证'
    if prerun==True:
        sub = '预跑 '+sub
    
    content = ''
    if check_rawdata_backup== True:
        content += u'rawdata %s 已备份成功.\n\n'%yesterday
    else:
        content += u'rawdata %s 备份失败.\n\n'%yesterday
    
    if errMsg==True:
        content += u'后台数据OK(%s)'%yesterday
        logging.info(content)
        #print content,type(content)
        check_data_script = os.path.join(current_dir,'zhimind_data_check.py')
        for group_type in (4,2,1,0):
            runScript = '/usr/bin/python %s --day %s --group_type %s --time_type %s'%(check_data_script,yesterday,group_type,timeType)
            logging.info(runScript)
            out = commands.getstatusoutput(runScript)
            content = content + '\n\n'+out[1].decode("utf-8")
            
            #print type(out[1])
            #myZhimindDataCheck.main(day=yesterday, timeType=timeType, groupType=group_type)
            
            
    else:
        content += u'后台数据ERROR(%s).\n'%yesterday
        logging.info(content)
        content += errMsg
        
        
        
    logging.info('start send mail.')
    mail_user = baseLocalConfig.emailConfig['user']
    mail_pass = baseLocalConfig.emailConfig['passwd']
    mail_host = baseLocalConfig.emailConfig['stmp']
    mail_postfix = baseLocalConfig.emailConfig['postfix']
    to_list = tolist.split(',')
    
    if errMsg==True and check_rawdata_backup==True:
        send_all = False
    else:
        send_all = True
    
    if send_all==False:
        sub +=' OK'
        logging.info(sub)
        ret = send_mail(mail_user, mail_pass, mail_host, mail_postfix,[to_list[0]] , sub, content)
        logging.info(str(ret))
    else:
        sub +=' Faild'
        logging.info(sub)
        ret = send_mail(mail_user, mail_pass, mail_host, mail_postfix,to_list , sub, content)
        logging.info(str(ret))